using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Rss;
using System.ServiceModel;

namespace LiveExpo
{
    public class LiveExpoProxy
    {
        public LiveExpoProxy()
        {

            
            
        
        }
        
        public List<Site> GetSites(string appKey)
        {
            BasicHttpBinding b = new BasicHttpBinding();
            EndpointAddress ea = new EndpointAddress("http://expo.live.com/API/Classifieds_Listings.asmx");
            b.MaxBufferSize = 2147483647;
            b.MaxReceivedMessageSize = 2147483647;
            b.ReaderQuotas.MaxStringContentLength = 2147483647;
            ChannelFactory<Classifieds_ListingsSoap> cf = new ChannelFactory<Classifieds_ListingsSoap>(b, ea);
            Classifieds_ListingsSoap client = cf.CreateChannel();


            GetSitesRequest request = new GetSitesRequest(new GetSitesRequestBody(appKey));
            GetSitesResponse response = new GetSitesResponse();
            response = client.GetSites(request);
            string sites = response.Body.GetSitesResult;
            
            
            sites = "<?xml version=\"1.0\" ?>" + sites;
            
            
            //<classifieds:sites xmlns:classifieds="http://expo.live.com/ns/2006/1.0">
            //    <classifieds:site classifieds:id="1" classifieds:name="SAMPLE_SITE" classifieds:baseUrl="http://expo.live.com"></classifieds:site>
            //    <classifieds:site classifieds:id="2" classifieds:name="UK_SITE" classifieds:baseUrl="http://uk.expo.live.com"></classifieds:site>
            //    <classifieds:site classifieds:id="3" classifieds:name="CN_SITE" classifieds:baseUrl="http://cn.expo.live.com"></classifieds:site>
            //</classifieds:sites>
            NameTable table = new NameTable();

            List<Site> sitesList = new List<Site>();

            System.Xml.XmlNamespaceManager mgr = new XmlNamespaceManager(table);

            mgr.AddNamespace("classifieds", "http://expo.live.com/ns/2006/1.0");

            System.Xml.XmlDocument resultXML = new System.Xml.XmlDocument(table);
            resultXML.LoadXml(sites);
            XmlNode sitesNodes = resultXML.SelectSingleNode("classifieds:sites",mgr);
            foreach (XmlNode siteNode in sitesNodes)
            {
                Site site = new Site();
                site.ID = siteNode.Attributes["classifieds:id"].InnerText;
                site.Name = siteNode.Attributes["classifieds:name"].InnerText;
                site.BaseUrl = siteNode.Attributes["classifieds:baseUrl"].InnerText;
                sitesList.Add(site);    
            
            }
            return sitesList;
        }




        public RssFeed GetListingsByMyBuddies(int siteId, string appKey, int page, int pageSize, string orderBy, bool orderAscending)
        {
            BasicHttpBinding b = new BasicHttpBinding();
            EndpointAddress ea = new EndpointAddress("http://expo.live.com/API/Classifieds_Listings.asmx");
            b.MaxBufferSize = 2147483647;
            b.MaxReceivedMessageSize = 2147483647;
            b.ReaderQuotas.MaxStringContentLength = 2147483647; 
            ChannelFactory<Classifieds_ListingsSoap> cf = new ChannelFactory<Classifieds_ListingsSoap>(b, ea);
            Classifieds_ListingsSoap client = cf.CreateChannel();
           

            ListingsByMyBuddiesRequest request = new ListingsByMyBuddiesRequest(new ListingsByMyBuddiesRequestBody(siteId, appKey, page, pageSize, orderBy, orderAscending));
            ListingsByMyBuddiesResponse response = new ListingsByMyBuddiesResponse();
            response = client.ListingsByMyBuddies(request);
            string listings = response.Body.ListingsByMyBuddiesResult;

            
            
            listings = "<?xml version=\"1.0\" ?>" + listings;
            RssFeed feed = new RssFeed(listings);
            foreach (RssItem item in feed.Channels[0].Items)
            {
                item.OriginatedFrom = "LiveExpo";
                item.Source = "LIVEEXPO";
            }
            return feed;
        
        }
        public RssFeed GetListingsByCategoryKeywordLocationV2(int siteId, string appKey, int page, int pageSize, string orderBy, bool orderAscending, int Category, string keyword, string city, string state, string postalCode, string Country, float maxDist, string transactionType)
        {


            BasicHttpBinding b = new BasicHttpBinding();
                        b.MaxBufferSize = 2147483647;
                        b.MaxReceivedMessageSize = 2147483647;
                        b.ReaderQuotas.MaxStringContentLength = 2147483647; 
            EndpointAddress ea = new EndpointAddress("http://expo.live.com/API/Classifieds_Listings.asmx");

            ChannelFactory<Classifieds_ListingsSoap> cf = new ChannelFactory<Classifieds_ListingsSoap>(b, ea);
            Classifieds_ListingsSoap client = cf.CreateChannel();

            ListingsByCategoryKeywordLocation_V2Request request = new ListingsByCategoryKeywordLocation_V2Request(new ListingsByCategoryKeywordLocation_V2RequestBody(siteId, appKey, page, pageSize, orderBy, orderAscending, Category, keyword, city, state, postalCode, Country, maxDist, transactionType));
            ListingsByCategoryKeywordLocation_V2Response response = new ListingsByCategoryKeywordLocation_V2Response();
            response = client.ListingsByCategoryKeywordLocation_V2(request);
            string listings = response.Body.ListingsByCategoryKeywordLocation_V2Result;
            listings = "<?xml version=\"1.0\" ?>" + listings;
            RssFeed feed = new RssFeed(listings);
            foreach (RssItem item in feed.Channels[0].Items)
            {
                item.OriginatedFrom = "LiveExpo";
                item.Source = "LIVEEXPO";
            }            
            return feed;
        
        
        }
        public RssFeed GetListingsByCategoryKeywordLocation(int siteId, string appKey, int page, int pageSize, string orderBy, bool orderAscending, int category, string keyword, double latitude, double longitude, float maxDist)
        {

            BasicHttpBinding b = new BasicHttpBinding();
            b.MaxBufferSize = 2147483647;
            b.MaxReceivedMessageSize = 2147483647;
            b.ReaderQuotas.MaxStringContentLength = 2147483647; 
            
            EndpointAddress ea = new EndpointAddress("http://expo.live.com/API/Classifieds_Listings.asmx");

            ChannelFactory<Classifieds_ListingsSoap> cf = new ChannelFactory<Classifieds_ListingsSoap>(b, ea);
            Classifieds_ListingsSoap client = cf.CreateChannel();

            //Classifieds_ListingsSoapClient client = new Classifieds_ListingsSoapClient();
            ListingsByCategoryKeywordLocationRequest request = new ListingsByCategoryKeywordLocationRequest(new ListingsByCategoryKeywordLocationRequestBody(siteId, appKey, page, pageSize, orderBy, orderAscending, category, keyword, latitude, longitude, maxDist));
            ListingsByCategoryKeywordLocationResponse response = new ListingsByCategoryKeywordLocationResponse();
            response = client.ListingsByCategoryKeywordLocation(request);
            string listings = response.Body.ListingsByCategoryKeywordLocationResult;
            
            listings = "<?xml version=\"1.0\" ?>" + listings;
            RssFeed feed = new RssFeed(listings);
            foreach (RssItem item in feed.Channels[0].Items)
            {
                item.OriginatedFrom = "LiveExpo";
                item.Source = "LIVEEXPO";
            }
            return feed;


        }
        public RssFeed GetListingsByUser(int siteId, string appKey, int page, int pageSize, string orderBy, bool orderAscending, string nickname)
        {
            BasicHttpBinding b = new BasicHttpBinding();
            b.MaxBufferSize = 2147483647;
            b.MaxReceivedMessageSize = 2147483647;
            b.ReaderQuotas.MaxStringContentLength = 2147483647; 
            
            EndpointAddress ea = new EndpointAddress("http://expo.live.com/API/Classifieds_Listings.asmx");

            ChannelFactory<Classifieds_ListingsSoap> cf = new ChannelFactory<Classifieds_ListingsSoap>(b, ea);
            Classifieds_ListingsSoap client = cf.CreateChannel();
            ListingsByUserRequest request = new ListingsByUserRequest(new ListingsByUserRequestBody(siteId, appKey, page, pageSize, orderBy, orderAscending, nickname));
            ListingsByUserResponse response = new ListingsByUserResponse();
            response = client.ListingsByUser(request);
            string listings = response.Body.ListingsByUserResult;

            listings = "<?xml version=\"1.0\" ?>" + listings;
            RssFeed feed = new RssFeed(listings);

            foreach (RssItem item in feed.Channels[0].Items)
            {
                item.OriginatedFrom = "LiveExpo";
                item.Source = "LIVEEXPO";
            }
            return feed;

        }
       

        public List<LiveExpoCategory> GetCategories(int siteID, string appKey )
        {

            BasicHttpBinding b = new BasicHttpBinding();
            b.MaxBufferSize = 2147483647;
            b.MaxReceivedMessageSize = 2147483647;
            b.ReaderQuotas.MaxStringContentLength = 2147483647;

            EndpointAddress ea = new EndpointAddress("http://expo.live.com/API/Classifieds_Listings.asmx");

            ChannelFactory<Classifieds_ListingsSoap> cf = new ChannelFactory<Classifieds_ListingsSoap>(b, ea);
            Classifieds_ListingsSoap client = cf.CreateChannel();
            GetCategoriesRequest request = new GetCategoriesRequest(new GetCategoriesRequestBody(siteID, appKey));
            GetCategoriesResponse response = new GetCategoriesResponse();
            response = client.GetCategories(request);
            string categories = response.Body.GetCategoriesResult;
            
            List<LiveExpoCategory> categoryList = new List<LiveExpoCategory>();

         
            //Console.WriteLine(categories);
            categories = "<?xml version=\"1.0\" ?>" + categories;

            try
            {

                NameTable table = new NameTable();


                System.Xml.XmlNamespaceManager mgr = new XmlNamespaceManager(table);

                mgr.AddNamespace("classifieds", "http://expo.live.com/ns/2006/1.0");

                System.Xml.XmlDocument resultXML = new System.Xml.XmlDocument(table);
                resultXML.LoadXml(categories);
                XmlNode categoriesNode = resultXML.SelectSingleNode("classifieds:categories",mgr);
                if (categoriesNode != null)
                {
                    foreach (XmlNode categoryNode in categoriesNode)
                    {
                        LiveExpoCategory category = new LiveExpoCategory();
                      //<classifieds:category classifieds:id="4" classifieds:name="Boats">
                      //    <classifieds:categoryAttributes>
                      //      <classifieds:attribute classifieds:name="STATE" classifieds:displayName="State" classifieds:type="String"></classifieds:attribute>
                      //      <classifieds:attribute classifieds:name="POSTALCODE" classifieds:displayName="Zip Code" classifieds:type="String"></classifieds:attribute>
                      //      <classifieds:attribute classifieds:name="PRIMARYCITY" classifieds:displayName="City" classifieds:type="String"></classifieds:attribute>
                      //      <classifieds:attribute classifieds:name="PRICE" classifieds:displayName="Price" classifieds:type="Float"></classifieds:attribute>
                      //      <classifieds:attribute classifieds:name="YEAR_BUILT" classifieds:displayName="Year built" classifieds:type="Number"></classifieds:attribute>
                      //      <classifieds:attribute classifieds:name="COLOR" classifieds:displayName="Color" classifieds:type="PickList">
                      //        <classifieds:attributeOption></classifieds:attributeOption>
                      //        <classifieds:attributeOption>Black</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Blue</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Brown</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Green</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Orange</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Purple</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Red</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Silver</classifieds:attributeOption>
                      //        <classifieds:attributeOption>White</classifieds:attributeOption>
                      //        <classifieds:attributeOption>Other</classifieds:attributeOption>
                      //      </classifieds:attribute>
                      //    </classifieds:categoryAttributes>
                      //    <classifieds:categoryTransactionTypes>
                      //      <classifieds:transactionType>For Sale</classifieds:transactionType>
                      //      <classifieds:transactionType>Wanted</classifieds:transactionType>
                      //      <classifieds:transactionType>Swap</classifieds:transactionType>
                      //      <classifieds:transactionType>Free</classifieds:transactionType>
                      //    </classifieds:categoryTransactionTypes>
                      //  </classifieds:category>


                        category = ProcessCategoryNode(categoryNode, mgr);
                       
                        categoryList.Add(category);

                    }



                }
            }
            catch (Exception)
            { }
        
            return categoryList;
        }

        private LiveExpoCategory ProcessCategoryNode(XmlNode categoryNode, XmlNamespaceManager mgr)
        {
            LiveExpoCategory category = new LiveExpoCategory();
            
            category.ID = categoryNode.Attributes["classifieds:id"].InnerText;
            category.Name = categoryNode.Attributes["classifieds:name"].InnerText;

            XmlNodeList attributesNodeList = categoryNode.SelectNodes("classifieds:categoryAttributes//classifieds:attribute", mgr);
            foreach (XmlNode attributeNode in attributesNodeList)
            {

                LiveExpoCategoryAttribute attribute = new LiveExpoCategoryAttribute();
                attribute.Name = attributeNode.Attributes["classifieds:name"].InnerText;
                attribute.DisplayName = attributeNode.Attributes["classifieds:displayName"].InnerText;
                attribute.Type = attributeNode.Attributes["classifieds:type"].InnerText;

                XmlNodeList optionsNodeList = attributeNode.SelectNodes("classifieds:attributeOption", mgr);
                foreach (XmlNode optionNode in optionsNodeList)
                {
                    attribute.Options.Add(optionNode.InnerText);
                }

                category.Attributes.Add(attribute);

            }

            XmlNodeList transactionTypeNodeList = categoryNode.SelectNodes("classifieds:categoryTransactionTypes//classifieds:transactionType", mgr);
            foreach (XmlNode transactionTypeNode in transactionTypeNodeList)
            {
                category.TransactionTypes.Add(transactionTypeNode.InnerText);

            }
        

            XmlNodeList subcategoriesNodeList = categoryNode.SelectNodes("classifieds:category", mgr);
            foreach(XmlNode subcategoryNode in subcategoriesNodeList)
            {
                LiveExpoCategory subcategory = ProcessCategoryNode(subcategoryNode, mgr);
                category.SubCategories.Add(subcategory);
            
            }

            return category;
        }
    
    }
}
